package com.example.textswitchtestdemo01.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.textswitchtestdemo01.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsUtil {

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private final List<String> totalItems;
    private boolean isLong = false;
    private String fileName = "news";
    private int fileMode = Context.MODE_PRIVATE;

    public NewsUtil(Context mContext) {
        totalItems = Arrays.asList(mContext.getResources().getStringArray(R.array.mobile_news_name));
        sp = mContext.getSharedPreferences(fileName, fileMode);
        editor = sp.edit();
        String current = sp.getString("current", "推荐,热点,科技,汽车资讯");
        editor.putString("current", current);
        editor.apply();
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public int getFileMode() {
        return fileMode;
    }

    public void setFileMode(int fileMode) {
        this.fileMode = fileMode;
    }

    public boolean isLong() {
        return isLong;
    }

    public void setLong(boolean aLong) {
        isLong = aLong;
    }

    public void saveCurrentItems(String item) {
        String current = sp.getString("current", null);
        if (!(current == null)) {
            editor.putString("current", current + "," + item);
        } else {
            editor.putString("current", item);
        }
        editor.apply();
    }

    public List<String> getCurrentItems() {
        String current = sp.getString("current", null);
        assert current != null;
        current = current.replace(",,", ",");
        return Arrays.asList(current.split(","));
    }

    public void clearAll() {
        editor.clear();
        editor.apply();
    }

    public static String change(List<String> stringArrayList) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String string : stringArrayList) {
            stringBuilder.append(string).append(",");
        }
        return stringBuilder.toString();
    }

    public void removeCurrentItems(String item) {
        List<String> currentItems = getCurrentItems();
        clearAll();
        ArrayList<String> mStrings = new ArrayList<>(currentItems);
        mStrings.remove(item);
        String change = change(mStrings);
        change = change.replace(",,", ",");
        saveCurrentItems(change);
    }

    public List<String> getWaitItems() {
        List<String> list = new ArrayList<>(totalItems);
        list.removeAll(getCurrentItems());
        return list;
    }


}
